package com.oJudge.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oJudge.common.ErrorCode;
import com.oJudge.constant.CommonConstant;
import com.oJudge.exception.BusinessException;
import com.oJudge.judge.JudgeService;
import com.oJudge.mapper.QuestionSubmitMapper;
import com.oJudge.model.dto.question_submit.QuestionSubmitAddRequest;
import com.oJudge.model.dto.question_submit.QuestionSubmitQueryRequest;
import com.oJudge.model.entity.Question;
import com.oJudge.model.entity.QuestionSubmit;
import com.oJudge.model.entity.User;
import com.oJudge.model.enums.QuestionSubmiStatusEnum;
import com.oJudge.model.enums.QuestionSubmitLanguageEnum;
import com.oJudge.model.vo.QuestionSubmitVO;
import com.oJudge.model.vo.QuestionVO;
import com.oJudge.model.vo.UserVO;
import com.oJudge.service.QuestionService;
import com.oJudge.service.QuestionSubmitService;
import com.oJudge.service.UserService;
import com.oJudge.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @description 针对表【question_submit(题目提交表)】的数据库操作Service实现
 * @createDate 2025-06-18 16:06:42
 */
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
        implements QuestionSubmitService {
    @Resource
    private QuestionService questionService;

    @Resource
    private UserService userService;

    @Resource
    @Lazy
    private JudgeService judgeService;

    /**
     * 提交题目
     *
     * @param questionSubmitAddRequest
     * @param loginUser
     * @return
     */
    @Override
    public long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {

        //获取数据
        Long questionId = questionSubmitAddRequest.getQuestionId();
        String language = questionSubmitAddRequest.getLanguage();
        String code = questionSubmitAddRequest.getCode();

        //编程语言校验
        QuestionSubmitLanguageEnum languageEnum = QuestionSubmitLanguageEnum.getEnumByValue(language);
        if (languageEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编程语言错误");
        }
        // 判断实体是否存在，根据类别获取实体
        Question question = questionService.getById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "未找到相关题目");
        }

        long userId = loginUser.getId();
        // 每个用户串行提交
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setUserId(userId);
        questionSubmit.setQuestionId(questionId);
        questionSubmit.setLanguage(language);
        questionSubmit.setCode(code);
        //设置初始状态
        questionSubmit.setStatus(QuestionSubmiStatusEnum.WAITING.getValue());
        questionSubmit.setJudgeInfo("{}");
        boolean save = this.save(questionSubmit);
        if (!save) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"数据插入失败");
        }
        Long id = questionSubmit.getId();
        CompletableFuture.runAsync(() -> {
            judgeService.doJudge(id);
        });
        return id;
    }

    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }
        // 获取所有查询条件
        Long userId = questionSubmitQueryRequest.getUserId();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();

        // 拼接查询条件
        queryWrapper.eq(StringUtils.isNotBlank(language), "language", language);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(QuestionSubmiStatusEnum.getEnumByValue(status) != null, "status", status);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }


    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User loginUser) {
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        long userId = loginUser.getId();
        //处理脱敏
        if (userId != questionSubmit.getUserId() && !userService.isAdmin(loginUser)) {
            questionSubmitVO.setCode(null);
        }
        return questionSubmitVO;
    }

    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, User loginUser) {
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        if (CollUtil.isEmpty(questionSubmitList)) {
            return questionSubmitVOPage;
        }
        //获取提交记录关联的用户信息,此处userIdList不使用Set,是因为listByIds查询列表的时候会自动去重(其查询语句类似于SELECT * FROM user WHERE id IN (1, 2, 3);)
        List<Long> userIdList = questionSubmitList.stream().map(QuestionSubmit::getUserId).collect(Collectors.toList());
        List<User> users = userService.listByIds(userIdList);
        Map<Long, UserVO> userVOMap = users.stream().collect(Collectors.toMap(User::getId, userService::getUserVO));
        //获取题目相关信息
        List<Long> questionIdList = questionSubmitList.stream().map(QuestionSubmit::getQuestionId).collect(Collectors.toList());
        List<Question> questionList = questionService.listByIds(questionIdList);
        Map<Long, QuestionVO> questionMap = questionList.stream().collect(Collectors.toMap(Question::getId, QuestionVO::objToVo));
        //获取提交记录关联的题目信息
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream()
                .map(questionSubmit -> {
                    QuestionSubmitVO questionSubmitVO = getQuestionSubmitVO(questionSubmit, loginUser);
                    questionSubmitVO.setUserVO(userVOMap.get(questionSubmit.getUserId()));
                    questionSubmitVO.setQuestionVO(questionMap.get(questionSubmit.getQuestionId()));
                    return questionSubmitVO;
                }).collect(Collectors.toList());

        questionSubmitVOPage.setRecords(questionSubmitVOList);
        return questionSubmitVOPage;
    }
}


